#include <sys/time.h>
#include "app_common.h"
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "log.h"



long app_common_get_curtime_ts()
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec * 1000 + tv.tv_usec / 1000;


}

/**
 * @brief 把字符打印为16进制字符串
 */
void app_common_print_hex(  char *data, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        printf("%02x ", data[i]);
    }
    printf("\n");

}

/**
 * @brief 把字符打印为16进制字符串 返回为字符串
 */
char *app_common_bytes_to_hexstr(  char *data, int len)
{
     char *hexstr = malloc(len * 2 + 1);
     int i;
     for (i = 0; i < len; i++)
     {
         sprintf(hexstr+i*2 ,"%02x", data[i]);
     }
     hexstr[len * 2] = '\0';
     return hexstr;

}

/**
 * @brief 把16进制字符串转换为字符数组
 * @param hexstr 16进制字符串
 * @param byte_buf 字节数组的容器
 * @param buf_len 字节数组的长度
 * @return 转换后的字节数组长度
 */
int app_common_hexstr_to_bytes(char *hexstr, char *byte_buf, int buf_len)
{
    int i;
    int len = strlen(hexstr);
    if(len/2 > buf_len  )
    {
        log_error("hexstr_to_bytes: buf_len is too small");
        return -1;
    }

    for(i = 0; i < len; i += 2)
    {
        sscanf(hexstr + i, "%2hhx", &byte_buf[i/2]);
    }
    return len / 2;

}
